﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SCS.Core.Models;
using SCS.Core.Models.ModelsFontend;
using SCS.Core.ViewModels;
using SCSService;
using System.Xml;
using SCSInternetBanking;
using SCS.Core.Models.CollectionFontend;

namespace SCS.Core.Controllers
{
    public class CheckoutController : BaseFontendController
    {
        //
        // GET: /Checkout/

        public ActionResult Payment()
        {
            IntPage();
            int siteGuid = 0;
            if (Request.Url.Host == "localhost")
            {
                siteGuid = DefaultSiteGuidGetter();
            }
            else
                siteGuid = Models.ConfigModel.GetWebsitebyDomain(DefaultHostGetter()).SiteGuid;

            int? LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
             if (Session["UserID"] == null)
             {
                if (DefaultHostGetter().Contains("localhost"))
                {
                    Session["NextAction"] = "/" + siteGuid + "/" + DefaultLanguageGetter() + "/Checkout/Payment";
                    return Redirect("/" + siteGuid + "/" + DefaultLanguageGetter() + "/UserWeb/SignIn");
                }
                else
                {
                    Session["NextAction"] = "/" + DefaultLanguageGetter() + "/Checkout/Payment";
                    return Redirect("/" + DefaultLanguageGetter() + "/UserWeb/SignIn");
                }
             }
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult Payments()
        {
            int siteGuid = 0;
            if (Request.Url.Host == "localhost")
            {
                 siteGuid = DefaultSiteGuidGetter();
            }
            else
            {
                 siteGuid = Models.ConfigModel.GetWebsitebyDomain(DefaultHostGetter()).SiteGuid;
            }
            var order = new Models.CollectionFontend.OrderCollection();
            Customer_Order GetCustomer_Order = HomeMasterModel.GetCustomer_OrdersByCustomerID(int.Parse(Session["UserID"].ToString()), siteGuid);
            try
            {
                if (GetCustomer_Order!=null)
                {
                order.Address = GetCustomer_Order.Address;
                order.City = GetCustomer_Order.City;
                order.Country = GetCustomer_Order.Country;
                order.Email = GetCustomer_Order.Email;
                order.PostalCode = GetCustomer_Order.PostalCode;
                order.Phone = GetCustomer_Order.Phone;
                order.FullName = GetCustomer_Order.Fullname;
                }
            }
            catch { }
            return PartialView("../BaseFontend/" + GetSiteGuid() + "/Payments", order);
            
        }

        //
        // POST: /Checkout/AddressAndPayment

        [ChildActionOnly]
        [HttpPost]
        public ActionResult Payments(FormCollection values)
        {
            int siteGuid = 0;
            string redirectStr = "";
            if (Request.Url.Host == "localhost")
            {
                siteGuid = DefaultSiteGuidGetter();
            }
            else
                siteGuid = Models.ConfigModel.GetWebsitebyDomain(DefaultHostGetter()).SiteGuid;

            int? LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());

            var order = new Models.CollectionFontend.OrderCollection();
            TryUpdateModel(order);

            try
            {
                if (Session["UserID"] != null && Session["LogInSite"]!=null)
                {
                    if (int.Parse(Session["LogInSite"].ToString()) == DefaultSiteGuidGetter())
                    {
                        SCSService.UserService userSvc = new UserService();
                        Customer_Order cusOrder = new Customer_Order();
                        cusOrder.CreateDate = DateTime.Now;
                        cusOrder.CustomerID = int.Parse(Session["UserID"].ToString());        //Luu ID cua khach hang sau khi dang nhap
                        cusOrder.Fullname = order.FullName;
                        cusOrder.Phone = order.Phone;
                        cusOrder.Email = order.Email;
                        cusOrder.Address = order.Address;
                        cusOrder.City = order.City;
                        cusOrder.Country = order.Country;
                        cusOrder.PostalCode = order.PostalCode;
                        cusOrder.OrderStatus = 0;   //0 la Order start
                        cusOrder.SiteGuid = GetSiteGuid();
                        cusOrder.Username = userSvc.GetUserByID(int.Parse(Session["UserID"].ToString())).UserName;  //User Name cua khach hang

                        //Save Order
                        ShoppingCart.AddOrder(cusOrder);

                        //Process the order
                        var cart = ShoppingCart.GetCart(this.HttpContext);
                        cart.CreateOrder(cusOrder, LanguageID);

                       // return RedirectToAction("Complete",new { id = cusOrder.OrderID });
                        if (DefaultHostGetter().Contains("localhost"))
                        {
                            redirectStr = "/" + siteGuid + "/" + DefaultLanguageGetter() + "/Checkout/Shipment/" + cusOrder.OrderID + "/?cketrue=" + Convert.ToInt32(order.CheckBoxAddress);
                        }
                        else
                        {
                            redirectStr = "/" + DefaultLanguageGetter() + "/Checkout/Shipment/" + cusOrder.OrderID + "/?cketrue=" + Convert.ToInt32(order.CheckBoxAddress);
                        }
                        
                    }
                    else
                    {
                        if (DefaultHostGetter().Contains("localhost"))
                        {
                            redirectStr="/" + siteGuid + "/" + DefaultLanguageGetter() + "/UserWeb/SignIn";
                        }
                        else
                        {
                            redirectStr="/" + DefaultLanguageGetter() + "/UserWeb/SignIn";
                        }
                    
                    }
                    
                }
                else
                {
                    if (DefaultHostGetter().Contains("localhost"))
                    {
                        redirectStr="/" + siteGuid + "/" + DefaultLanguageGetter() + "/UserWeb/SignIn";
                    }
                    else
                    {
                        redirectStr="/" + DefaultLanguageGetter() + "/UserWeb/SignIn";
                    }
                   
                }
                    

            }
            catch
            {
                //Invalid - redisplay with errors
                //return View(order);
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/Payments", order);
            }
            //ViewData["redirectStr"] = redirectStr;
            //return PartialView("../BaseFontend/" + GetSiteGuid() + "/Shipments");
            ViewData["redirectStr"] = redirectStr;
            return PartialView("../Commont/ResultOrder");
            
            //return RedirectToAction("Shipment");
        }

        public ActionResult Shipment(int? id, int? cketrue)
        {
            IntPage();
            int siteGuid = 0;
            if (Request.Url.Host == "localhost")
            {
                siteGuid = DefaultSiteGuidGetter();
            }
            else
                siteGuid = Models.ConfigModel.GetWebsitebyDomain(DefaultHostGetter()).SiteGuid;

            int? LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            if (Session["UserID"] == null)
            {
                if (DefaultHostGetter().Contains("localhost"))
                {
                    Session["NextAction"] = "/" + siteGuid + "/" + DefaultLanguageGetter() + "/Checkout/Shipment";
                    return Redirect("/" + siteGuid + "/" + DefaultLanguageGetter() + "/UserWeb/SignIn");
                }
                else
                {
                    Session["NextAction"] = "/" + DefaultLanguageGetter() + "/Checkout/Shipment";
                    return Redirect("/" + DefaultLanguageGetter() + "/UserWeb/SignIn");
                }
            }
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult Shipments(int id, int? cketrue)
        {
            //id is OrderID
            var ship = new Models.CollectionFontend.ShipmentCollection();
            ship.OrderID = id;
            Customer_Order order = ShoppingCart.GetOrderByID(id);
            if (cketrue == 1)
            {
    
                ship.Address = order.Address;
                ship.City = order.City;
                ship.Country = order.Country;
                ship.FullName = order.Fullname;
                ship.Phone = order.Phone;
                ship.PostalCode = order.PostalCode;
                ship.Email = order.Email;
               

            }
            ViewData["OrderID"] = id;
            return PartialView("../BaseFontend/" + GetSiteGuid() + "/Shipments", ship);

        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult Shipments(FormCollection values)
        {
            
            int siteGuid = 0;
            string redirectStr = "";
            if (Request.Url.Host == "localhost")
            {
                siteGuid = DefaultSiteGuidGetter();
            }
            else
                siteGuid = Models.ConfigModel.GetWebsitebyDomain(DefaultHostGetter()).SiteGuid;

            int? LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());

            var ship = new Models.CollectionFontend.ShipmentCollection();
            TryUpdateModel(ship);

            try
            {
                if (Session["UserID"] != null && Session["LogInSite"] != null)
                {
                    if (int.Parse(Session["LogInSite"].ToString()) == DefaultSiteGuidGetter())
                    {
                       
                        //Create Shipment
                        SCSService.Shipment shipment = new Shipment();
                        shipment.FullName = ship.FullName;
                        shipment.Status = ship.Status;
                        shipment.CreateDate = DateTime.Now;
                        shipment.Address = ship.Address;
                        shipment.Phone = ship.Phone;
                        shipment.Email = ship.Email;
                        shipment.PostalCode = ship.PostalCode;
                        shipment.City = ship.City;
                        shipment.Country = ship.Country;
                        shipment.OrderID = ship.OrderID;

                        var shipID= ShoppingCart.AddShipment(shipment);

                       
                        // return RedirectToAction("Complete",new { id = cusOrder.OrderID });
                        if (DefaultHostGetter().Contains("localhost"))
                        {
                            redirectStr = "/" + siteGuid + "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrder/" + ship.OrderID;
                        }
                        else
                        {
                            redirectStr = "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrder/" + ship.OrderID;
                        }

                    }
                    else
                    {
                        if (DefaultHostGetter().Contains("localhost"))
                        {
                            redirectStr = "/" + siteGuid + "/" + DefaultLanguageGetter() + "/UserWeb/SignIn";
                        }
                        else
                        {
                            redirectStr = "/" + DefaultLanguageGetter() + "/UserWeb/SignIn";
                        }

                    }

                }
                else
                {
                    if (DefaultHostGetter().Contains("localhost"))
                    {
                        redirectStr = "/" + siteGuid + "/" + DefaultLanguageGetter() + "/UserWeb/SignIn";
                    }
                    else
                    {
                        redirectStr = "/" + DefaultLanguageGetter() + "/UserWeb/SignIn";
                    }

                }


            }
            catch
            {
                //Invalid - redisplay with errors
                //return View(order);
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/Shipments", ship);
            }
            ViewData["redirectStr"] = redirectStr;
            return PartialView("../Commont/ResultOrder");
        }

        public ActionResult PaymentOrder(int? id)
        {
            IntPage();
            ViewData["OrderID"] = id;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult PaymentMethods(int? id)
        {
            BaseService baseSvc = new BaseService();
            //var ship = new Models.CollectionFontend.ShipmentCollection();
            int? languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            var cart = ShoppingCart.GetCart(this.HttpContext);
            int siteGuid = GetSiteGuid();

            Guid invoiceCode = Guid.NewGuid();
            //string invoiceCode = "abc";//baseSvc.RandomString(5, true);

            //create Invoice
            SCSService.Invoice invoice = new Invoice();
            invoice.OrderID = id;
            invoice.Status = 0;     //0 is status start payment
            invoice.CreateDate = DateTime.Now;
            invoice.CreateUser = int.Parse(Session["UserID"].ToString());       //checkout with ID login || ID of Customer Vang lai
            invoice.InvoiceCode = baseSvc.ConvertString(invoiceCode.ToString());
            invoice.TotalPrice = cart.GetTotalValueCartItem(languageId);
            invoice.TotalProduct = cart.GetCountProductInOrder((int)id);
            invoice.PaymentDate = DateTime.Now;

            long invoiceID = ShoppingCart.CreateInvoice(invoice);

            //update tempOrderID for cart
            List<Cart> listCartItem = ShoppingCart.GetListCartItemByShoppingCartID(cart.shoppingCartId);
            foreach (var car in listCartItem)
            {
                car.TempOrderID = id;
                ShoppingCart.UpdateTempOrderIDforCart(car);
            }

            // Set up our ViewModel
            var viewModel = new PaymentMethodViewModels
            {
                MethodItems = cart.GetListPaymentMethod(siteGuid),
                CartItems = cart.GetListCartItemByCartID(),
                CartTotal = cart.GetTotalValueCartItem(languageId),
                Invoice=invoice
            };
            return PartialView("../BaseFontend/" + GetSiteGuid() + "/PaymentMethods", viewModel);

        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult PaymentMethods(string id)
        {

            int? languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            var cart = ShoppingCart.GetCart(this.HttpContext);
            Cart ca = ShoppingCart.GetCartByCartID(cart.shoppingCartId);
            int orderID=ca.TempOrderID??0;
            int siteGuid = GetSiteGuid();
            string redirectStr = "";
            if (id == "1")
            {
                //Payment success
                if (DefaultHostGetter().Contains("localhost"))
                {
                    redirectStr = "/" + siteGuid + "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrderConfirm/" + orderID + "," + "1";
                }
                else
                {
                    redirectStr = "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrderConfirm/" + orderID + "," + "1";
                }
            }
            else if (id == "2")
            {
                //Payment faild
                //Giao dịch lỗi
                Invoice invoice = ShoppingCart.GetInvoiceByOrderID(orderID);
                invoice.Status = 2;       //0 start; 1 success; 2 faild ; 3 send Order not payment online
                invoice.PaymentDate = DateTime.Now;
                //Update Status for Invoice
                ShoppingCart.UpdateInvoiceStatus(invoice);

                Customer_Order order = ShoppingCart.GetOrderByID(orderID);
                order.OrderStatus = 2;    //0 start; 1 success; 2 faild ; 3 send Order not payment online
                //Update Status for Order
                ShoppingCart.UpdateOrderStatus(order);

                //Create Payment
                Payment pay = new Payment();
                pay.InvoiceID = invoice.InvoiceID;
                pay.Status = 2;                         //1 success;2 transaction faild
                pay.Amount = invoice.TotalPrice;
                pay.CreateDate = DateTime.Now;

                int payId = ShoppingCart.CreatePayment(pay);

                
                if (DefaultHostGetter().Contains("localhost"))
                {
                    redirectStr = "/" + siteGuid + "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrderConfirm/" + orderID + "," + "2";
                }
                else
                {
                    redirectStr = "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrderConfirm/" + orderID + "," + "2";
                }

            }

            ViewData["redirectStr"] = redirectStr;
            return PartialView("../Commont/ResultOrder");
        }

        public ActionResult PaymentOrderResultForNL()
        {
            //Page return result form Ngan Luong
            IntPage();
            return View();
        }
       

        [ChildActionOnly]
        [HttpGet]
        public ActionResult PaymentOrderResultsForNL()
        {
            //Method get (method received result from Ngan Luong)  
            //Only Ngan Luong
            int? languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            var cart = ShoppingCart.GetCart(this.HttpContext);
            Cart ca = ShoppingCart.GetCartByCartID(cart.shoppingCartId);
            int orderID = ca.TempOrderID ?? 0;
            int siteGuid = GetSiteGuid();
            string redirectStr = "";

            String transaction_info = Request.QueryString["transaction_info"];
            String order_code = Request.QueryString["order_code"];
            String payment_id = Request.QueryString["payment_id"];
            String payment_type = Request.QueryString["payment_type"];
            String secure_code = Request.QueryString["secure_code"];
            String price = Request.QueryString["price"];
            String error_text = Request.QueryString["error_text"];
            SCSInternetBanking.NganLuong.NL_Checkout nl = new SCSInternetBanking.NganLuong.NL_Checkout();
            bool check = nl.verifyPaymentUrl(transaction_info, order_code, price, payment_id, payment_type, error_text, secure_code);

            if (check)
            {
                //Payment success
                if (DefaultHostGetter().Contains("localhost"))
                {
                    redirectStr = "/" + siteGuid + "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrderConfirm/" + orderID + "," + "1";
                }
                else
                {
                    redirectStr = "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrderConfirm/" + orderID + "," + "1";
                }
            }
            else if (!check)
            {
                //Payment faild
                //Giao dịch lỗi
                Invoice invoice = ShoppingCart.GetInvoiceByOrderID(orderID);
                invoice.Status = 2;       //0 start; 1 success; 2 faild ; 3 send Order not payment online
                invoice.PaymentDate = DateTime.Now;
                //Update Status for Invoice
                ShoppingCart.UpdateInvoiceStatus(invoice);

                Customer_Order order = ShoppingCart.GetOrderByID(orderID);
                order.OrderStatus = 2;    //0 start; 1 success; 2 faild ; 3 send Order not payment online
                //Update Status for Order
                ShoppingCart.UpdateOrderStatus(order);

                //Create Payment
                Payment pay = new Payment();
                pay.InvoiceID = invoice.InvoiceID;
                pay.Status = 2;                         //1 success;2 transaction faild
                pay.Amount = invoice.TotalPrice;
                pay.CreateDate = DateTime.Now;

                int payId = ShoppingCart.CreatePayment(pay);


                if (DefaultHostGetter().Contains("localhost"))
                {
                    redirectStr = "/" + siteGuid + "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrderConfirm/" + orderID + "," + "2";
                }
                else
                {
                    redirectStr = "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrderConfirm/" + orderID + "," + "2";
                }

            }

            ViewData["redirectStr"] = redirectStr;
            return PartialView("../Commont/ResultOrder");
        }

        public JsonResult CancelPaymentTimeOut()
        {
            //Cancel Transaction timeout
            int? languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            var cart = ShoppingCart.GetCart(this.HttpContext);
            Cart ca = ShoppingCart.GetCartByCartID(cart.shoppingCartId);
            int orderID = ca.TempOrderID ?? 0;
            int siteGuid = GetSiteGuid();

            //Payment faild
            //Giao dịch lỗi
            Invoice invoice = ShoppingCart.GetInvoiceByOrderID(orderID);
            invoice.Status = 4;       //0 start; 1 success; 2 faild ; 3 send Order not payment online; 4 transaction timeout
            invoice.PaymentDate = DateTime.Now;
            //Update Status for Invoice
            ShoppingCart.UpdateInvoiceStatus(invoice);

            Customer_Order order = ShoppingCart.GetOrderByID(orderID);
            order.OrderStatus = 4;    //0 start; 1 success; 2 faild ; 3 send Order not payment online; 4 transaction timeout
            //Update Status for Order
            ShoppingCart.UpdateOrderStatus(order);

            ////Create Payment
            //Payment pay = new Payment();
            //pay.InvoiceID = invoice.InvoiceID;
            //pay.Status = 4;                         //1 success;2 transaction faild
            //pay.Amount = invoice.TotalPrice;
            //pay.CreateDate = DateTime.Now;

            //int payId = ShoppingCart.CreatePayment(pay);

            return Json("1");
        }

        public ActionResult PaymentOrderResult(string id)
        {
            IntPage();
            ViewData["StatusCheckOutResult"] = id;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult PaymentOrderResults(string id)
        {

            int? languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            var cart = ShoppingCart.GetCart(this.HttpContext);
            Cart ca = ShoppingCart.GetCartByCartID(cart.shoppingCartId);
            int orderID = ca.TempOrderID ?? 0;
            int siteGuid = GetSiteGuid();
            string redirectStr = "";
            if (id == "1")
            {
                //Payment success
                if (DefaultHostGetter().Contains("localhost"))
                {
                    redirectStr = "/" + siteGuid + "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrderConfirm/" + orderID + "," + "1";
                }
                else
                {
                    redirectStr = "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrderConfirm/" + orderID + "," + "1";
                }
            }
            else if (id == "2")
            {
                //Payment faild
                //Giao dịch lỗi
                Invoice invoice = ShoppingCart.GetInvoiceByOrderID(orderID);
                invoice.Status = 2;       //0 start; 1 success; 2 faild ; 3 send Order not payment online
                invoice.PaymentDate = DateTime.Now;
                //Update Status for Invoice
                ShoppingCart.UpdateInvoiceStatus(invoice);

                Customer_Order order = ShoppingCart.GetOrderByID(orderID);
                order.OrderStatus = 2;    //0 start; 1 success; 2 faild ; 3 send Order not payment online
                //Update Status for Order
                ShoppingCart.UpdateOrderStatus(order);

                //Create Payment
                Payment pay = new Payment();
                pay.InvoiceID = invoice.InvoiceID;
                pay.Status = 2;                         //1 success;2 transaction faild
                pay.Amount = invoice.TotalPrice;
                pay.CreateDate = DateTime.Now;

                int payId = ShoppingCart.CreatePayment(pay);


                if (DefaultHostGetter().Contains("localhost"))
                {
                    redirectStr = "/" + siteGuid + "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrderConfirm/" + orderID + "," + "2";
                }
                else
                {
                    redirectStr = "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrderConfirm/" + orderID + "," + "2";
                }

            }

            ViewData["redirectStr"] = redirectStr;
            return PartialView("../Commont/ResultOrder");
        }

        public ActionResult PaymentOrderConfirm(string id)
        {
            IntPage();
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult OrderConfirm(string id)
        {
            var invoices = new Models.CollectionFontend.InvoiceCollection();
            Invoice inv = ShoppingCart.GetInvoiceByOrderID(int.Parse(id.Split(',')[0]));
            //id is OrderID
            if (id.Split(',')[1] == "3")
            { 
                //GDH
            }
            else if (id.Split(',')[1] == "1" || id.Split(',')[1] == "2")
            { 
                //Payment with LR
            }

                invoices.OrderID = int.Parse(id.Split(',')[0]);
                invoices.Status = byte.Parse(id.Split(',')[1]);
                invoices.InvoiceID = inv.InvoiceID;
                invoices.InvoiceCode = inv.InvoiceCode;
                invoices.TotalPrice = inv.TotalPrice;
                invoices.TotalProduct = inv.TotalProduct;
                invoices.Price = inv.Price;
                invoices.CreateDate = inv.CreateDate;
                invoices.CreateUser = inv.CreateUser;
                invoices.Description = inv.Description;
                invoices.PaymentDate = DateTime.Now;
                invoices.TotalDiscounts = inv.TotalDiscounts;
                invoices.TransactionsID = inv.TransactionsID;
                ViewData["OrderID"] = id.Split(',')[0];
                ViewData["Status"] = id.Split(',')[1];
            
            return PartialView("../BaseFontend/" + GetSiteGuid() + "/OrderConfirm",invoices);

        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult OrderConfirm(FormCollection values)
        {

            int siteGuid = 0;
            string redirectStr = "";
            if (Request.Url.Host == "localhost")
            {
                siteGuid = DefaultSiteGuidGetter();
            }
            else
                siteGuid = Models.ConfigModel.GetWebsitebyDomain(DefaultHostGetter()).SiteGuid;

            int? LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());

            var invoices = new Models.CollectionFontend.InvoiceCollection();
            TryUpdateModel(invoices);


                if (Session["UserID"] != null && Session["LogInSite"] != null)
                {
                    if (int.Parse(Session["LogInSite"].ToString()) == DefaultSiteGuidGetter())
                    {

                        Customer_Order order = ShoppingCart.GetOrderByID(invoices.OrderID);
                        if (order != null)
                        {
                            

                            if (invoices.Status == 3)
                            { 
                                //GDH
                                //Not Create Payment

                                Invoice invoice = ShoppingCart.GetInvoiceByOrderID(order.OrderID);
                                invoice.Status = invoices.Status;       //0 start; 1 success; 2 faild ; 3 send Order not payment online
                                invoice.PaymentDate = DateTime.Now;
                                //Update Status for Invoice
                                ShoppingCart.UpdateInvoiceStatus(invoice);

                                order.OrderStatus = invoices.Status;    //0 start; 1 success; 2 faild ; 3 send Order not payment online
                                //Update Status for Order
                                ShoppingCart.UpdateOrderStatus(order);
                            }
                            else if (invoices.Status == 1 || invoices.Status == 2)
                            { 
                                //Payment with LR
                                if (invoices.Status == 1)
                                {
                                    Invoice invoice = ShoppingCart.GetInvoiceByOrderID(order.OrderID);
                                    invoice.Status = invoices.Status;       //0 start; 1 success; 2 faild ; 3 send Order not payment online
                                    invoice.PaymentDate = DateTime.Now;
                                    //Update Status for Invoice
                                    ShoppingCart.UpdateInvoiceStatus(invoice);

                                    order.OrderStatus = invoices.Status;    //0 start; 1 success; 2 faild ; 3 send Order not payment online
                                    //Update Status for Order
                                    ShoppingCart.UpdateOrderStatus(order);


                                    //Create Payment
                                    Payment pay = new Payment();
                                    pay.InvoiceID = invoice.InvoiceID;
                                    pay.Status = 1;                         //1 success;2 transaction faild
                                    pay.Amount = invoice.TotalPrice;
                                    pay.CreateDate = DateTime.Now;

                                    int payId = ShoppingCart.CreatePayment(pay);

                                    //Send Invoice to Email


                                }


                                if (invoices.Status == 1)
                                {
                                    if (DefaultHostGetter().Contains("localhost"))
                                    {
                                        redirectStr = "/" + siteGuid + "/" + DefaultLanguageGetter() + "/Checkout/Complete/" + invoices.Status;
                                    }
                                    else
                                    {
                                        redirectStr = "/" + DefaultLanguageGetter() + "/Checkout/Complete/" + invoices.Status;
                                    }
                                }
                                else if (invoices.Status == 2)
                                {
                                    if (DefaultHostGetter().Contains("localhost"))
                                    {
                                        redirectStr = "/" + siteGuid + "/" + DefaultLanguageGetter() + "/Product/ListProduct";
                                    }
                                    else
                                    {
                                        redirectStr = "/" + DefaultLanguageGetter() + "/Product/ListProduct";
                                    }
                                }
                            }
                            
                        }

                        

                    }
                    else
                    {
                        if (DefaultHostGetter().Contains("localhost"))
                        {
                            redirectStr = "/" + siteGuid + "/" + DefaultLanguageGetter() + "/UserWeb/SignIn";
                        }
                        else
                        {
                            redirectStr = "/" + DefaultLanguageGetter() + "/UserWeb/SignIn";
                        }

                    }

                }
                else
                {
                    if (DefaultHostGetter().Contains("localhost"))
                    {
                        redirectStr = "/" + siteGuid + "/" + DefaultLanguageGetter() + "/UserWeb/SignIn";
                    }
                    else
                    {
                        redirectStr = "/" + DefaultLanguageGetter() + "/UserWeb/SignIn";
                    }

                }

            ViewData["redirectStr"] = redirectStr;
            return PartialView("../Commont/ResultOrder");
        }

        public ActionResult Complete(int? id)
        {
            IntPage();
            return View();
        }


        [ChildActionOnly]
        [HttpGet]
        public ActionResult Completes(int? id)
        {

            int? languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            var cart = ShoppingCart.GetCart(this.HttpContext);
            Cart ca = ShoppingCart.GetCartByCartID(cart.shoppingCartId);
            int orderID = ca.TempOrderID ?? 0;
            int siteGuid = GetSiteGuid();
            if (id == 1)
            {
                //Payment success
                Invoice invoice = ShoppingCart.GetInvoiceByOrderID(orderID);

                Customer_Order order = ShoppingCart.GetOrderByID(orderID);
                List<SCSService.Product> listProduct = ShoppingCart.GetListProductByOrderID(orderID);

                ViewData["ListProduct"] = listProduct;
                ViewData["OrderID"] = orderID;
                
            }
            else if (id == 2)
            {
                //Payment faild
                
            }
            else if (id == 3)
            { 
                //GDH
            }
            //empty cart
            cart.EmptyCart();
            return PartialView("../BaseFontend/" + GetSiteGuid() + "/Completes");
        }

    }
}
